import 'dart:async';


class BackgroundTaskManager {
  BackgroundTaskManager._();
  static final BackgroundTaskManager instance = BackgroundTaskManager._();

  /// 无参 IO 任务
  Future<T> submitIo<T>(FutureOr<T> Function() task) async {
    try {
      return await task();
    } catch (e, st) {
      _logError('IO Task', e, st);
      rethrow;
    }
  }

  /// 带参数 IO 任务
  Future<T> submitIoWithParam<T, P>(
      FutureOr<T> Function(P param) task, {
        required P param,
      }) async {
    try {
      return await task(param);
    } catch (e, st) {
      _logError('IO Task with param', e, st);
      rethrow;
    }
  }

  /// 无参 CPU 任务
  Future<T> submitCpu<T>(T Function() task) async {
    try {
      return await Future<T>.delayed(Duration.zero, task);
    } catch (e, st) {
      _logError('CPU Task', e, st);
      rethrow;
    }
  }

  /// 带参数 CPU 任务
  Future<T> submitCpuWithParam<T, P>(
      T Function(P param) task, {
        required P param,
      }) async {
    try {
      return await Future<T>.delayed(Duration.zero, () => task(param));
    } catch (e, st) {
      _logError('CPU Task with param', e, st);
      rethrow;
    }
  }

  void _logError(String type, Object e, StackTrace st) {
    print('[$type] Error: $e\n$st');
  }
}

